package com.lims.admin.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;


import javacommon.base.*;
import javacommon.util.ComparatorMenu;
import javacommon.util.MD5;
import javacommon.util.TextTool;

import cn.org.rapid_framework.page.*;

import com.lims.admin.model.*;
import com.lims.admin.service.*;
import com.lims.admin.vo.query.*;
import com.lims.landInfo.service.LandDictionaryManager;

/**
 * @author zzh
 */
@SuppressWarnings({"serial","unchecked"})
public class UserAction extends BaseStruts2Action implements Preparable,ModelDriven{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	//forward paths
	protected static final String QUERY_JSP = "/pages/admin/User/query.jsp";
	protected static final String LIST_JSP= "/pages/admin/User/list.jsp";
	protected static final String INDEX_JSP= "/pages/index.jsp";
	private static final String HOME_JSP = "/pages/home.jsp";
	private static final String LOGIN_JSP = "/Login.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/pages/admin/User/list.do";
	
	private UserManager userManager;
	private LandDictionaryManager landDictionaryManager;
	
	private User user;
	java.lang.String id = null;
	private String items;

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			user = new User();
		} else {
			user = (User)userManager.getById(id);
		}
	}
	
	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setUserManager(UserManager manager) {
		this.userManager = manager;
	}	
	
	public void setLandDictionaryManager(LandDictionaryManager landDictionaryManager){
		this.landDictionaryManager = landDictionaryManager;
	}
	
	public Object getModel() {
		return user;
	}
	
	public void setObjid(java.lang.String val) {
		this.id = val;
	}

	public void setItems(String items) {
		this.items = items;
	}
	
	/**进入登录后主界面**/
	public String index(){
		return INDEX_JSP;
	}
	
	/**主界面中的包含第一页**/
	public String home() {
		return HOME_JSP;
	}
	
	/**用户登录验证**/
	public String login(){
		HttpServletRequest request = this.getRequest();
		HttpSession session = request.getSession();
		User sessionUser = (User) session.getAttribute("user");
		if(TextTool.isNotNull(sessionUser)) {
			return INDEX_JSP;
		} 
		String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		String ccode = (String) request.getParameter("ccode");
		String msg = "";
		if(TextTool.isNotNull(ccode) && ccode.trim().equals(code)){
			User u = this.userManager.checkLogin(this.user);
			if(TextTool.isNull(u)) {
				msg ="用户名或密码错。<br/>";
				request.setAttribute("msg", msg);
				return LOGIN_JSP;
			} else {
				//重新整理Menus [parentMenu :[{},{}],]
				sortMenus(u);
				session.setAttribute("user", u);
				//取所有的字典，缓存至session中
				Map map = this.landDictionaryManager.findAllToMap();
				session.setAttribute("dicMap", map);
				return INDEX_JSP;
			}
		}else {
			msg ="验证码不正确。<br/>";
			request.setAttribute("msg", msg);
			return LOGIN_JSP;
		}
	}
	
	//整理menus
	private void sortMenus(User u) {
		Map<String, Menu> map = new HashMap<String, Menu>();
		for (Iterator iterator = u.getMenus().iterator(); iterator.hasNext();) {
			Menu m = (Menu) iterator.next();
			Menu pm = m.getParentMenu();
			Menu pp = map.get(pm.getObjid());
			if(pp == null) {
				List<Menu> mlist = new ArrayList<Menu>();
				mlist.add(m);
				pm.setMenus(mlist);
				map.put(pm.getObjid(), pm);
			} else {
				pp.getMenus().add(m);
			}
		}
		List newList= new ArrayList();
		Set keySet = map.keySet();
		for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			newList.add(map.get(key));
		}
		//重新排序
		Comparator<Menu> comparator = new ComparatorMenu();
		for (Iterator iterator = newList.iterator(); iterator.hasNext();) {
			Menu m = (Menu) iterator.next();
			List mlist = m.getMenus();
			Collections.sort(mlist,comparator);
		}
		Collections.sort(newList,comparator);
		u.setMenus(newList);
	}
	/**
	 * 退出登录
	 * @return
	 */
	public String loginOut() {
		HttpServletRequest request = this.getRequest();
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		return LOGIN_JSP;
	}
	
	/** 执行搜索 */
	public String list() {
		UserQuery query = newQuery(UserQuery.class,DEFAULT_SORT_COLUMNS);
		Page page = userManager.findPage(query);
		savePage(page,query);
		return LIST_JSP;
	}
	
	/** 保存新增对象 */
	public String save() {
		user.setPassword(MD5.pwdToMD5(user.getPassword()));
		userManager.save(user);
		//Flash.current().success(CREATED_SUCCESS); //存放在Flash中的数据,在下一次http请求中仍然可以读取数据,error()用于显示错误消息
		return LIST_ACTION;
	}
	
	/**保存更新对象*/
	public String update() {
		user.setPassword(MD5.pwdToMD5(user.getPassword()));
		userManager.update(this.user);
		//Flash.current().success(UPDATE_SUCCESS);
		return LIST_ACTION;
	}
	
	/**删除对象*/
	public String delete() {
		String[] objids = items.split(",");
		for (int i = 0; i < objids.length; i++) {
			userManager.removeById(objids[i]);
		}
		//Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}
	
}
